import { Button, Modal, Space, Table } from "antd";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import type { TableProps } from "antd";
import dayjs from "@/utils/dayjs";
import { TZ } from "@/utils/env";
import { changeModal, changeParams, changeSelectedRowKeys, getListAsync } from "@/store/withdrawRecord/withdrawRecordSlice";
import { submit } from "@/store/withdrawRecord/withdrawRecordAPI";

export interface DataType {
  uuid: string;
  amount: number,
  c_time: number,
  career_withdraw: number,
  ic_code: string,
  ic_reason: string,
  ic_source: number,
  id: number,
  invite_revenue: number,
  method_to_addr: string,
  real_revenue: number,
  status: number,
  trade_id: string,
  tran_no: string,
  user_id: number,
  wd_way: number,
  currency_sign: string
}

export default function MTable() {
  const dispatch = useAppDispatch();
  const { params, table, selectedRowKeys } = useAppSelector((state) => state.withdrawRecord);
  const {
    config: { data: { data: { user_channel_list = [], wd_order_status = [], wd_way_conf
      = [] } = {} } = {} } = {},
  } = useAppSelector((state) => state.app);

  const columns: TableProps<DataType>["columns"] = [
    {
      title: "id",
      key: "id",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "时间",
      key: "c_time",
      dataIndex: "c_time",
      align: "center",
      render: (text) => dayjs.unix(text).tz(TZ).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "渠道",
      key: "channel",
      dataIndex: "channel",
      align: "center",
      render: (text) =>
        user_channel_list?.find?.((i) => i.value === text)?.label,
    },
    {
      title: "地区",
      key: "country",
      dataIndex: "country",
      align: "center",
    },
    {
      title: "用户id",
      key: "user_id",
      dataIndex: "user_id",
      align: "center",
    },
    {
      title: "金额",
      key: "amount",
      dataIndex: "amount",
      align: "center",
      render: (text, record) => `${record.currency_sign}${text}`
    },
    {
      title: "生涯提现",
      key: "career_withdraw",
      dataIndex: "career_withdraw",
      align: "center",
    },
    {
      title: "自动拦截原因",
      key: "auto_reason",
      dataIndex: "auto_reason",
      align: "center",
    },
    {
      title: "拦截原因",
      key: "ic_reason",
      dataIndex: "ic_reason",
      align: "center",
    },
    {
      title: "邀请收益",
      key: "invite_revenue",
      dataIndex: "invite_revenue",
      align: "center",
    },
    {
      title: "到账地址",
      key: "method_to_addr",
      dataIndex: "method_to_addr",
      align: "center",
    },
    {
      title: "生涯盈利",
      key: "real_revenue",
      dataIndex: "real_revenue",
      align: "center",
    },
    {
      title: "状态",
      key: "status",
      dataIndex: "status",
      align: "center",
      render: (text) =>
        wd_order_status?.find?.((i) => i.value === text)?.label,
    },
    {
      title: "订单号",
      key: "trade_id",
      dataIndex: "trade_id",
      align: "center",
    },
    {
      title: "服务器订单号",
      key: "tran_no",
      dataIndex: "tran_no",
      align: "center",
    },
    {
      title: "提现渠道",
      key: "wd_way",
      dataIndex: "wd_way",
      align: "center",
      render: (text) =>
        wd_way_conf?.find?.((i) => i.value === text)?.label,
    },
    {
      title: '操作',
      key: 'opt',
      dataIndex: 'opt',
      align: 'center',
      fixed: 'right',
      render: (_text, record) => {
        return <Button.Group size="small">
          <Button disabled={record.status !== 1} type="primary" ghost onClick={() => handlePass([record.id])}>通过</Button>
          <Button disabled={record.status !== 1} type="primary" danger onClick={() => handleReject([record.id])}>拒绝</Button>
        </Button.Group>
      }
    }
  ];

  const handlePass = (ids: number[]) => {
    Modal.confirm({
      title: '确认通过吗',
      onOk: () => new Promise<void>((resolve, reject) => {
        submit({
          wd_status: 3,
          wd_list_str: JSON.stringify(ids)
        }).then(() => {
          resolve()
          dispatch(getListAsync({...params}))
          dispatch(changeSelectedRowKeys([]))
        }).catch(reject)
      })
    })
  }

  const handleReject = (ids: number[]) => {
    dispatch(changeModal({
      open: true,
      wd_list_str: ids
    }))
  }

  return (
    <Space direction="vertical" className="w-full">
      <Space wrap>
        <Button disabled={!selectedRowKeys.length} type="primary" ghost onClick={() => handlePass(selectedRowKeys as number[])}>批量通过</Button>
        <Button disabled={!selectedRowKeys.length} type="primary" danger onClick={() => handleReject(selectedRowKeys as number[])}>批量拒绝</Button>
      </Space>
      <Table
        rowSelection={{
          fixed: true,
          type: 'checkbox',
          getCheckboxProps: (record) => {
            return {
              disabled: record.status !== 1
            }
          },
          selectedRowKeys,
          onChange: (selectedRowKeys) => {
            dispatch(changeSelectedRowKeys(selectedRowKeys))
          }
        }}
        columns={columns}
        scroll={{ x: "max-content" }}
        bordered
        loading={table.status === "loading"}
        pagination={{
          total: table?.data?.data?.total,
          current: params?.page,
          pageSize: params?.page_size,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total: number, range: [number, number]): string =>
            `${range[0]}-${range[1]}条/共${total}条`,
          onChange: (page: number, pageSize: number): void => {
            dispatch(changeParams({ page, page_size: pageSize }));
            dispatch(
              getListAsync({
                ...params,
                page,
                page_size: pageSize,
              })
            );
          },
        }}
        dataSource={table?.data?.data?.data || []}
        size="small"
        rowKey="id"
      />
    </Space>
  );
}
